package de.metalcon.gwt.server.db.nodes;

import java.util.HashMap;
import java.util.Map;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;

import de.metalcon.gwt.server.db.ANode;
import de.metalcon.gwt.server.db.Indexes;

public class Type extends ANode {
	private final char typePrefix;

	@SuppressWarnings({ "rawtypes", "serial" })
	private static final Map<Character, Class> ALL_TYPES = new HashMap<Character, Class>() {
		{
			put('u', User.class);
			// put('a', Album.class);
			// ...
		}
	};

	public Type(Node node) {
		super(node);
		typePrefix = getGlobalKey().charAt(0);
	}

	public Type(GraphDatabaseService db, char typePrefix) {
		super(db, "");
		this.typePrefix = typePrefix;
	}

	@Override
	public char getTypePrefix() {
		return this.typePrefix;
	}

	public static Type GetTypeNode(GraphDatabaseService db, char typePrefix) {
		return (Type) Get(db, "", typePrefix);
	}

	public static void GenerateTypeNodes(GraphDatabaseService db) {
		for (char prefix : ALL_TYPES.keySet()) {
			Type t = GetTypeNode(db, prefix);
			if (t == null) {
				String globalKey = GenerateGlobalKey("", prefix);
				Index<Node> nodes = Indexes.anyNode.getIndex(db);

				Transaction tx = db.beginTx();
				try {
					Node node = db.createNode();
					node.setProperty("GlobalKey", globalKey);
					nodes.add(node, "GlobalKey", globalKey);
					tx.success();
				} finally {
					tx.finish();
				}
			}
		}
	}

	@Override
	public Type getTypeNode() {
		return null;
	}

	/**
	 * 
	 * @param prefix
	 *            The prefix of the type to be returned
	 * @return The Class of the Type node with the requested prefix
	 */
	@SuppressWarnings("rawtypes")
	public static Class GetTypeClassByPrefix(char prefix) {
		return ALL_TYPES.get(prefix);
	}

	@Override
	protected HashMap<String, Class> getAllowedProperties() {
		return null;
	}
}